package com.jf3q.sup.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jf3q.sup.domain.Positions;
import com.jf3q.sup.service.PositionsService;
import com.jf3q.sup.utils.Constant;
import com.jf3q.sup.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("positions")
public class PositionsController {

    @Autowired
    private PositionsService positionsService;
    /**
     * 分页查询
     */

    @PreAuthorize("hasAnyAuthority('/positions')")
    @GetMapping("")
    public ResultVo getPage(String name, @RequestParam(defaultValue = "1") Integer pageNum){
        IPage<Positions> page = Page.of(pageNum, Constant.PAGE_SIZE);
        positionsService.page(page,
                new LambdaQueryWrapper<Positions>().like(StringUtils.isNotEmpty(name),Positions::getName,name));
        return ResultVo.success(null,page);
    }

    /**
     * 修改查询
     */
    @PreAuthorize("hasAnyAuthority('/positions/add')")
    @PostMapping("")
    public ResultVo save(@RequestBody Positions Positions){
        try {
            positionsService.save(Positions);
        } catch (Exception e) {
            throw new RuntimeException("新增岗位出问题啦!"+e.getMessage());
        }
        return ResultVo.success("新增岗位成功",null);
    }


    @PreAuthorize("hasAnyAuthority('/positions/edit')")
    @PutMapping("")
    public ResultVo edit(@RequestBody Positions Positions){
        try {
            positionsService.updateById(Positions);
        } catch (Exception e) {
            throw new RuntimeException("修改岗位出问题啦!"+e.getMessage());
        }
        return ResultVo.success("修改岗位成功",null);
    }


    @PreAuthorize("hasAnyAuthority('/positions/delete')")
    @DeleteMapping("{id}")
    public ResultVo del(@PathVariable Integer id){
        try {
            positionsService.removeById(id);
        } catch (Exception e) {
            throw new RuntimeException("此信息数据与其他数据相连，请先删除与其他关联的数据再进行操作！");
        }
        return ResultVo.success("刪除岗位成功",null);
    }
}
